package cn.tedu.vrd07.controller;

import cn.tedu.vrd07.entity.Product;
import cn.tedu.vrd07.entity.User;
import cn.tedu.vrd07.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/product/")
public class ProductController {
    @Autowired(required = false)
    ProductMapper mapper;

    @RequestMapping("insert")
    public int insert(Product product, MultipartFile picFile, HttpSession session) throws IOException {
        User user= (User) session.getAttribute("user");
        if (user==null){//代表未登录
            return 2;
        }

        System.out.println("product = " + product + ", picFile = " + picFile);

        String filrName=picFile.getOriginalFilename();
        String suffix=filrName.substring(filrName.lastIndexOf("."));
        filrName= UUID.randomUUID()+suffix;
        String dirPath="e:/upload/vrd";
        //得到和日期相关的路径
        SimpleDateFormat format=new SimpleDateFormat("/yyyy/MM/dd/");
        //把当前时间按照指定的格式进行转换 /2021/10/19
        String datePath=format.format(new Date());
        //得到保存图片文件夹的路径 e:/upload/vrd/2021/10/19
        File dirFile=new File(dirPath+datePath);
        //如果不存在则创建
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        //得到完整的文件路径
        String filePath=dirPath+datePath+filrName;
        //保存上传的文件
        picFile.transferTo(new File(filePath));
        //图片路径添加到product对象里面
        product.setUrl(datePath+filrName);
        //title,author,intro,category,url, 日期,
        product.setCreated(new Date());
        mapper.insert(product);
        return 1;
    }
    @RequestMapping("select")
    public List<Product>select(){
        return mapper.select();
    }
    @RequestMapping("delete")
    public void delete(int id){
         mapper.delete(id);
    }
}
